package com.seocoo.worker.order;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.contrarywind.view.WheelView;
import com.jaeger.library.StatusBarUtil;
import com.seocoo.worker.R;
import com.seocoo.worker.base.multiImage.BaseListImageFragment;
import com.seocoo.worker.base.multiImage.RspImage;
import com.seocoo.worker.friend.entity.RxEvaluateSuccess;
import com.seocoo.worker.order.entity.RspOrderInstallDetail;
import com.seocoo.worker.order.entity.RspWorkers;
import com.seocoo.worker.order.entity.RxCancelInstallSuccess;
import com.seocoo.worker.order.model.OrderInstallDetailModel;
import com.seocoo.worker.order.model.OrderModel;
import com.seocoo.worker.order.req.ReqOrderInstallDetail;
import com.seocoo.worker.order.widget.OrderDetailAddressView;
import com.seocoo.worker.order.widget.OrderDetailCommodityView;
import com.seocoo.worker.order.widget.OrderDetailParticularsView;
import com.seocoo.worker.order.widget.OrderDetailReceivingView;
import com.seocoo.worker.order.widget.OrderDetailWorkerView;
import com.seocoo.worker.order.widget.rsp.RspOrderDetailAddress;
import com.seocoo.worker.order.widget.rsp.RspOrderDetailParticulars;
import com.sfh.lib.event.BusEvent;
import com.sfh.lib.event.BusEventManager;
import com.sfh.lib.mvvm.LiveDataMatch;
import com.sfh.lib.ui.MVVMActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * author : Ssp
 * date   : 2020/2/22 23:54
 * desc   : 订单详情
 */
public class OrderGoldDetailActivity extends MVVMActivity implements View.OnClickListener {

    private OrderDetailReceivingView order_receiving;
    private OrderDetailAddressView order_address;
    private OrderDetailParticularsView order_particulars;
    private OrderDetailCommodityView order_commodity;
    private OrderDetailParticularsView order_measure;
    private OrderDetailParticularsView install_info;
    private OrderDetailWorkerView worker_info;
    private TextView tv_remark;
    private String orderId;
    private TextView tv_title;
    private ImageView ivBack;
    private RspOrderInstallDetail mRspData;
    private TextView tv_cancel;
    private TextView tv_receiving;
    private TextView tv_appointment_install_time;
    private TextView tv_input_measure_time;
    private TextView tv_measure_time;
    private LinearLayout ll_remark;
    private LinearLayout ll_img;
    private BaseListImageFragment upLoadFileFragment;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderGoldDetailActivity.class);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gold_order_detail_activity);
        orderId = getIntent().getStringExtra("orderId");
        initView();
        StatusBarUtil.setTranslucentForImageView(this, 0, tv_title);
        initListener();
        reFreshData();

    }

    private void reFreshData() {
        getViewModel(OrderInstallDetailModel.class).refreshData(new ReqOrderInstallDetail(orderId));
    }

    @LiveDataMatch
    public void onQuerySuccess(RspOrderInstallDetail data) {
        mRspData = data;
        if (TextUtils.isEmpty(data.getRemark())) {
            ll_remark.setVisibility(View.GONE);
        } else {
            ll_remark.setVisibility(View.VISIBLE);
            tv_remark.setText(data.getRemark());
        }
        tv_remark.setText(data.getRemark());
        initOrderDetailReceivingViewData(data);
        initOrderDetailAddressViewData(data);
        initOrderDetailParticularsViewData(data);
        initOrderDetailCommodityViewData(data);
        if (!TextUtils.equals("101", data.getOrderStatus())) {
            initOrderDetailMeasureViewData(data);
        }
        initInstallMeasureViewData(data);
        initWorksViewData(data);
        initBottomView(data);
        String[] picList = data.getPicList();
        if (picList == null || picList.length == 0) {
            ll_img.setVisibility(View.GONE);
        } else {
            ll_img.setVisibility(View.VISIBLE);
            assert upLoadFileFragment != null;
            upLoadFileFragment.setImageCount(3, picList.length, false);
            upLoadFileFragment.setTv_title1("现场图片上传");
            upLoadFileFragment.setTv_title2("");
            ArrayList<RspImage> list = new ArrayList<>();
            for (String s : picList) {
                RspImage rspImage = new RspImage();
                rspImage.setFullPath(s);
                list.add(rspImage);
            }
            upLoadFileFragment.setNewData(list);
        }
    }

    private void initWorksViewData(RspOrderInstallDetail data) {
        List<RspWorkers> workers = data.getWorkers();
        if (workers == null || workers.size() == 0) {
            worker_info.setVisibility(View.GONE);
        } else {
            worker_info.setVisibility(View.VISIBLE);
            worker_info.setTv_title("关联工友");
            worker_info.initData(workers);
        }
    }

    @LiveDataMatch
    public void onTakeOrder(String orderId) {
        BusEventManager.postEvent(new RxCancelInstallSuccess(true));
        finish();
    }

    @LiveDataMatch
    public void onCancelMeasure(String measureId) {
        BusEventManager.postEvent(new RxCancelInstallSuccess(true));
        finish();
    }

    @LiveDataMatch
    public void onAddOrderMeasure() {
        BusEventManager.postEvent(new RxCancelInstallSuccess(true));
        finish();
    }

    @BusEvent(from = "刷新列表")
    public void refresh1(RxEvaluateSuccess result) {
        if (result.isSuccess()) {
            reFreshData();
        }
    }

    @BusEvent(from = "刷新列表")
    public void refresh2(RxCancelInstallSuccess result) {
        if (result.isCancelSuccess()) {
            reFreshData();
        }
    }

    @SuppressLint("CutPasteId")
    private void initView() {
        tv_title = findViewById(R.id.tv_title);
        ivBack = findViewById(R.id.iv_back);
        order_receiving = findViewById(R.id.order_receiving);
        order_address = findViewById(R.id.order_address);
        order_particulars = findViewById(R.id.order_particulars);
        order_commodity = findViewById(R.id.order_commodity);
        order_measure = findViewById(R.id.order_measure);
        worker_info = findViewById(R.id.worker_info);
        tv_remark = findViewById(R.id.tv_remark);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_measure_time = findViewById(R.id.tv_measure_time);
        tv_receiving = findViewById(R.id.tv_receiving);
        tv_appointment_install_time = findViewById(R.id.tv_appointment_install_time);
        tv_input_measure_time = findViewById(R.id.tv_input_measure_time);
        install_info = findViewById(R.id.install_info);
        ll_remark = findViewById(R.id.ll_remark);
        ll_img = findViewById(R.id.ll_img);
        upLoadFileFragment = (BaseListImageFragment) getSupportFragmentManager().findFragmentById(R.id.upLoadFileFragment);
    }

    private void initListener() {
        tv_cancel.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tv_receiving.setOnClickListener(this);
        tv_input_measure_time.setOnClickListener(this);
        tv_measure_time.setOnClickListener(this);
    }

    private void initOrderDetailReceivingViewData(RspOrderInstallDetail data) {
        //订单状态 400 取消安装 401 待接单 402 待取货 403 待安装 501 待评价
        String orderStatus = "";
        if (TextUtils.equals("101", data.getOrderStatus())) {
            orderStatus = "待接单";
        }
        if (TextUtils.equals("201", data.getOrderStatus())) {
            orderStatus = "测量进行中";
        }
        if (TextUtils.equals("301", data.getOrderStatus())) {
            orderStatus = "等待买家付款";
        }
        // （400 401 402) 待取货
        if (TextUtils.equals("400", data.getOrderStatus())) {
            orderStatus = "待取货";
        }
        if (TextUtils.equals("401", data.getOrderStatus())) {
            orderStatus = "待取货";
        }
        if (TextUtils.equals("402", data.getOrderStatus())) {
            orderStatus = "待取货";
        }
        if (TextUtils.equals("403", data.getOrderStatus())) {
            orderStatus = "待安装";
        }
        if (TextUtils.equals("501", data.getOrderStatus())) {
            orderStatus = "等待评价工友";
        }
        if (TextUtils.equals("502", data.getOrderStatus())) {
            orderStatus = "已评价";
        }
        order_receiving.initData(data.getCommission(), orderStatus);
        order_receiving.setTv1_1Text("测量佣金");
    }

    private void initOrderDetailAddressViewData(RspOrderInstallDetail data) {
        RspOrderDetailAddress rspOrderDetailAddress = new RspOrderDetailAddress();
        rspOrderDetailAddress.setCargoAddress(data.getMerchantName());
        rspOrderDetailAddress.setCargoAddressDetail(data.getMerchantProvince() + data.getMerchantCity() + data.getMerchantDistrict() + data.getMerchantAddress());
        rspOrderDetailAddress.setUserAddress(data.getUserProvince() + data.getUserCity() + data.getUserDistrict() + data.getUserCommunity() + data.getUserDoorPlate());
        rspOrderDetailAddress.setUserName(data.getConsignee());
        rspOrderDetailAddress.setUserPhone(data.getContact());
        rspOrderDetailAddress.setMerchantContact(data.getMerchantContact());
        rspOrderDetailAddress.setPickupCode("");
        String orderStatus = data.getOrderStatus();
        if (TextUtils.isEmpty(orderStatus) || TextUtils.equals("101", orderStatus)) {
            order_address.setVisibilityPhone(View.GONE);
        }
        order_address.initData(rspOrderDetailAddress);
    }

    private void initOrderDetailCommodityViewData(RspOrderInstallDetail data) {
        order_commodity.initData(data.getGoodsList(), data.getOrderStatus());
        order_commodity.setScoreName(data.getMerchantName());
    }

    private void initOrderDetailParticularsViewData(RspOrderInstallDetail data) {

        order_particulars.setTv_title("订单详情");
        List<RspOrderDetailParticulars> list = new ArrayList<>();
        RspOrderDetailParticulars rsp1 = new RspOrderDetailParticulars();
        rsp1.setName("订单编号：");
        rsp1.setContent(data.getOrderNo());
        list.add(rsp1);
        RspOrderDetailParticulars rsp2 = new RspOrderDetailParticulars();
        rsp2.setName("下单时间：");
        rsp2.setContent(data.getAddTime());
        list.add(rsp2);
        String orderPrice = data.getOrderPrice();
        if (!TextUtils.isEmpty(orderPrice)) {
            Double aDouble = Double.valueOf(orderPrice);
            if (aDouble > 0) {
                RspOrderDetailParticulars rsp3 = new RspOrderDetailParticulars();
                rsp3.setName("订单总额：");
                rsp3.setContent(orderPrice);
                list.add(rsp3);
            }
        }

        String orderStatus = data.getOrderStatus();
        if (TextUtils.equals(orderStatus, "403") || TextUtils.equals(orderStatus, "501") || TextUtils.equals(orderStatus, "502")) {

            String payTime = data.getPayTime();
            RspOrderDetailParticulars rsp4 = new RspOrderDetailParticulars();
            rsp4.setName("支付时间：");
            rsp4.setContent(payTime);
            list.add(rsp4);
            String channelType = data.getChannelType();
            // 支付方式1-微信2-支付宝
            RspOrderDetailParticulars rsp5 = new RspOrderDetailParticulars();
            rsp5.setName("支付方式：");
            if (TextUtils.equals("2", channelType)) {
                channelType = "微信支付";
                rsp5.setContent(channelType);
                list.add(rsp5);
            }
            if (TextUtils.equals("1", channelType)) {
                channelType = "支付宝支付";
                rsp5.setContent(channelType);
                list.add(rsp5);
            }
        }

        String pickupCode = data.getPickupCode();
        if (!TextUtils.isEmpty(pickupCode)) {
            RspOrderDetailParticulars rsp6 = new RspOrderDetailParticulars();
            rsp6.setName("取货码：");
            rsp6.setContent(pickupCode);
            list.add(rsp6);
        }
        order_particulars.initData(list);
    }

    private void initOrderDetailMeasureViewData(RspOrderInstallDetail data) {

        order_measure.setTv_title("测量详情");
        List<RspOrderDetailParticulars> list = new ArrayList<>();
        RspOrderDetailParticulars rsp1 = new RspOrderDetailParticulars();
        rsp1.setName("接单时间：");
        rsp1.setContent(data.getMeasureCreatedTime());
        list.add(rsp1);

        if (!TextUtils.isEmpty(data.getMeasureTime())) {
            RspOrderDetailParticulars rsp3 = new RspOrderDetailParticulars();
            rsp3.setName("预约测量时间：");
            rsp3.setContent(data.getMeasureTime());
            list.add(rsp3);
        }

        order_measure.initData(list);

    }

    private void initInstallMeasureViewData(RspOrderInstallDetail data) {

        install_info.setTv_title("安装详情");
        List<RspOrderDetailParticulars> list = new ArrayList<>();
        String installUserName = data.getInstallUserName();
        if (TextUtils.isEmpty(installUserName)) {
            installUserName = "";
        }
        RspOrderDetailParticulars rsp1 = new RspOrderDetailParticulars();
        rsp1.setName("工匠姓名：");
        rsp1.setContent(installUserName);
        list.add(rsp1);

        String level = data.getLevel();
        if (TextUtils.isEmpty(level)) {
            level = "";
        }
        RspOrderDetailParticulars rsp2 = new RspOrderDetailParticulars();
        rsp2.setName("星级等级：");
        rsp2.setContent(level);
        list.add(rsp2);

        String installCreatedTime = data.getInstallCreatedTime();
        if (TextUtils.isEmpty(installCreatedTime)) {
            installCreatedTime = "";
        }
        RspOrderDetailParticulars rsp3 = new RspOrderDetailParticulars();
        rsp3.setName("接单时间：");
        rsp3.setContent(installCreatedTime);
        list.add(rsp3);

        String installTime = data.getInstallTime();
        if (TextUtils.isEmpty(installTime)) {
            installTime = "";
        }
        RspOrderDetailParticulars rsp4 = new RspOrderDetailParticulars();
        rsp4.setName("已预约安装时间：");
        rsp4.setContent(installTime);
        list.add(rsp4);
        String status = data.getOrderStatus();
        if (TextUtils.equals("501", status) || TextUtils.equals("502", status)) {
            String finishTime = data.getFinishTime();
            RspOrderDetailParticulars rsp5 = new RspOrderDetailParticulars();
            rsp5.setName("安装完成时间：");
            rsp5.setContent(finishTime);
            list.add(rsp5);
        }

        install_info.initData(list);


        if (TextUtils.isEmpty(status)) {
            status = "0";
        }
        int parseInt = Integer.parseInt(status);
        if (parseInt >= 402) {
            install_info.setVisibility(View.VISIBLE);
        } else {
            install_info.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View view) {

        if (mRspData == null) {
            return;
        }

        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_cancel:
                //取消测量
                getViewModel(OrderModel.class).cancelMeasure(mRspData.getMeasureId());
                break;
            case R.id.tv_receiving:
                //接单
                getViewModel(OrderModel.class).takeOrder(mRspData.getOrderId());
                break;
            case R.id.tv_input_measure_time:
                //输入测量结果
                OrderGoldMeasureActivity.start(this, mRspData.getOrderId());
                break;
            case R.id.tv_measure_time:
                //设置测量时间
                initTimeSelect("设置测量时间", (date, v) -> {
                    String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                    @SuppressLint("SimpleDateFormat") String format = new SimpleDateFormat(strDateFormat).format(date);
                    getViewModel(OrderModel.class).setMeasureTime(mRspData.getOrderId(), format, mRspData.getMeasureId());
                });
                break;
            default:
                break;
        }
    }

    /**
     * 选择时间
     */
    @SuppressLint("SimpleDateFormat")
    private void initTimeSelect(String title, OnTimeSelectListener timeSelectListener) {
        long timeMillis = System.currentTimeMillis();
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        SimpleDateFormat moth = new SimpleDateFormat("MM");
        SimpleDateFormat day = new SimpleDateFormat("dd");
        Date date = new Date(timeMillis);
        Calendar startDate = Calendar.getInstance();
        startDate.set(Integer.parseInt(year.format(date)), Integer.parseInt(moth.format(date)) - 1, Integer.parseInt(day.format(date)));
        Calendar endDate = Calendar.getInstance();
        endDate.set(2080, 12, 30);
        Calendar selectedDate = Calendar.getInstance();
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(this, timeSelectListener)
                .setTitleText(title)
                //时间选择器 ，自定义布局
                .setDividerColor(Color.parseColor("#999999"))
                .setDividerType(WheelView.DividerType.FILL)
                .setContentTextSize(18)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                //设置选中项的颜色
                .setTextColorCenter(Color.parseColor("#333333"))
                .isCenterLabel(false)
                .setLabel("年", "月", "日", "时", "分", "")
                //设置两横线之间的间隔倍数  m
                .setLineSpacingMultiplier(2.0f)
                .isDialog(true)//是否显示为对话框样式
                .setTextXOffset(0, 0, 0, 0, 0, 0)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, true, true, false});
        timePickerBuilder.build().show();
    }

    private void initBottomView(RspOrderInstallDetail data) {

        //301 待付款-无
        //402 待取货-无
        //501 待评价-无
        //502 已评价-无
        String status = data.getOrderStatus();
        String measureTime = data.getMeasureTime();
        if (TextUtils.equals("201", status) && TextUtils.isEmpty(measureTime)) {
            //201 测量中-取消测量、设置测量时间（测量时间为空的时候）
            tv_measure_time.setVisibility(View.VISIBLE);
        } else {
            tv_measure_time.setVisibility(View.GONE);
        }

        if (TextUtils.equals("201", status) || TextUtils.equals("202", status)) {
            //201 202 测量中-取消测量、设置测量时间（测量时间为空的时候）
            tv_cancel.setVisibility(View.VISIBLE);
        } else {
            tv_cancel.setVisibility(View.GONE);
        }

        if (TextUtils.equals("201", status) && !TextUtils.isEmpty(measureTime)) {
            //201 测量中-输入测量结果（测量时间不为空）
            tv_input_measure_time.setVisibility(View.VISIBLE);
        } else {
            tv_input_measure_time.setVisibility(View.GONE);
        }

        if (TextUtils.equals("101", status)) {
            //101 待接单-接单
            tv_receiving.setVisibility(View.VISIBLE);
        } else {
            tv_receiving.setVisibility(View.GONE);
        }
        boolean a = TextUtils.equals("400", status);
        boolean b = TextUtils.equals("401", status);
        boolean d = !TextUtils.isEmpty(data.getInstallTime());

        if ((a || b) && d) {
            //400 401 403 待安装-根据预约安装时间（ installTime）不为空展示 “已预约安装时间”
            tv_appointment_install_time.setVisibility(View.VISIBLE);
        } else {
            tv_appointment_install_time.setVisibility(View.GONE);
        }
    }
}
